package com.sgb.kjwl.view.ui.activity.leaseAsk.fragment;

import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.FragmentPublishLease2Binding;
import com.sgb.kjwl.model.entity.PublishLeaseDataEntity;
import com.sgb.kjwl.utils.EditInputFilter;
import com.sgb.kjwl.viewmodel.machine.AskLeaseCommonModel;
import com.sgb.kjwl.viewmodel.machine.PublishLeaseInfoModel2;
import com.swgk.core.customview.CfkEditView;
import com.swgk.core.customview.ItemInputTextView;
import com.swgk.core.util.MToast;
import com.swgk.core.util.PickSelectEntity;

import java.util.ArrayList;
import java.util.List;

public class PublishLeashInfoFragment2 extends Fragment implements ItemInputTextView.OnWholeItemClickListener {

    private FragmentPublishLease2Binding binding;
    private PublishLeaseInfoModel2 viewModel;
    private AskLeaseCommonModel commonModel;

    private int type;
    private String id = "";
    private List<PickSelectEntity> invoiceGGDatas = new ArrayList<>();//发票类型
    private List<PickSelectEntity> shuilvDatas = new ArrayList<>();//税率
    private List<PickSelectEntity> timeTypeData = new ArrayList<>();
    private OptionsPickerView pickerView1, pickerView2, pickerView3;
    private List<PublishLeaseDataEntity.ParamBean> viewList = new ArrayList<>();//自定义参数

    public void onAttach(Context context) {
        super.onAttach(context);
        id = getArguments().getString("id");
        type = getArguments().getInt("type");
    }

    public static PublishLeashInfoFragment2 newInstance(String id, int type) {
        PublishLeashInfoFragment2 frag = new PublishLeashInfoFragment2();
        Bundle bundle = new Bundle();
        bundle.putString("id", id);
        bundle.putInt("type", type);
        frag.setArguments(bundle);
        return frag;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_publish_lease_2, container, false);
        binding.setLifecycleOwner(this);
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        viewModel = new ViewModelProvider(getActivity()).get(PublishLeaseInfoModel2.class);
        commonModel = new ViewModelProvider(this).get(AskLeaseCommonModel.class);
        initView();
        initData();
        receiverLiveData();
        showDetail();
    }

    private void showDetail() {
        if (!TextUtils.isEmpty(id)) {
            PublishLeaseDataEntity.AttachDTO attachDTO = viewModel.bean.getAttach();
            if (attachDTO.getInvoiceType() != null) {
                if (attachDTO.getInvoiceType().equals("0")) {
                    binding.itvInvoiceType.setContent("普通发票");
                    binding.itvShuiLv.setVisibility(View.VISIBLE);
                    binding.itvShuiLv.setContent(viewModel.bean.getAttach().getTariff());
                } else if (attachDTO.getInvoiceType().equals("1")) {
                    binding.itvInvoiceType.setContent("专用发票");
                    binding.itvShuiLv.setVisibility(View.VISIBLE);
                    binding.itvShuiLv.setContent(attachDTO.getTariff() );
                } else if (attachDTO.getInvoiceType().equals("2")) {
                    binding.itvInvoiceType.setContent("不需要发票");
                    binding.itvShuiLv.setVisibility(View.GONE);//不需要发票时隐藏税率
                }
            }

            binding.tvDay.setText(attachDTO.getWarrantyPeriodUnit());
            binding.etWarrantyMoney.setText(attachDTO.getWarranty());
            binding.etWarrantyTime.setText(attachDTO.getWarrantyPeriod());
            binding.marginMoney.setText(attachDTO.getPerformanceBond());
            binding.driverSalaryBonus.setEditContent(attachDTO.getDriverSalaryBonus());
            binding.driverStaying.setEditContent(attachDTO.getDriverStaying());
            binding.fuelCosts.setEditContent(attachDTO.getFuelCosts());
            binding.repairCosts.setEditContent(attachDTO.getRepairCosts());
            binding.entryExitFees.setEditContent(attachDTO.getEntryExitFees());
            binding.sparePartsCost.setEditContent(attachDTO.getSparePartsCost());
            binding.maintenanceCost.setEditContent(attachDTO.getMaintenanceCost());
            binding.insuranceFee.setEditContent(attachDTO.getInsuranceFee());
            binding.accident.setEditContent(attachDTO.getAccident());
            //附加字段返显
            if (attachDTO.getExtra() != null && attachDTO.getExtra().size() > 0) {
                for (int i = 0; i < viewModel.bean.getAttach().getExtra().size(); i++) {
                    PublishLeaseDataEntity.ParamBean param = attachDTO.getExtra().get(i);
                    View view = View.inflate(getActivity(), R.layout.layout_lease_ask_item, null);
                    ((EditText) view.findViewById(R.id.tv_desc_title)).setText(param.getTitle());
                    ((CfkEditView) view.findViewById(R.id.tv_desc_content)).setEditContent(param.getContent());
                    binding.llDescGroup.addView(view, i);
                    //删除按钮
                    TextView tvDel = (TextView) view.findViewById(R.id.tv_del);
                    tvDel.setVisibility(View.VISIBLE);
                    tvDel.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            binding.llDescGroup.removeView(view);
                        }
                    });
                    if (i == viewModel.bean.getAttach().getExtra().size() - 1) {
                        tvDel.setVisibility(View.GONE);
                        binding.tvAddView.setVisibility(View.VISIBLE);
                        binding.tvDelView.setVisibility(View.VISIBLE);
                    }
                }
            }
        }
    }

    private void initData() {
        timeTypeData = commonModel.getTimeTypeData();
        invoiceGGDatas = commonModel.getInvoiceData();
        commonModel.getLeaseRate();
        showPop1();
        showPop2();
        showPop3();
    }

    private void receiverLiveData() {
        commonModel.showRateLiveData.observe(getViewLifecycleOwner(), t -> shuilvDatas.addAll(t));

    }

    private void initView() {
        binding.setType(type);
        binding.beforeAndNextStepItem.tvNextStep.setOnClickListener(v -> {
            if (submit())
                viewModel.selectFragLiveData.postValue(2);
        });
        binding.beforeAndNextStepItem.tvBeforeStep.setOnClickListener(v -> {
            if (submit())
                viewModel.selectFragLiveData.postValue(0);
        });
        binding.beforeAndNextStepItem.tvSubmit.setOnClickListener(v -> {
            if (submit())
                viewModel.getequimentLeasing();
        });
        binding.tvDay.setOnClickListener(v -> pickerView3.show());
        binding.ivArrrow.setOnClickListener(v -> pickerView3.show());
        binding.itvInvoiceType.setOnWholeItemClickListener(this);
        binding.itvShuiLv.setOnWholeItemClickListener(this);
        binding.tvAddView.setOnClickListener(v -> addView());
        binding.tvDelView.setOnClickListener(v -> delView());
        binding.etWarrantyMoney.setFilters(new EditInputFilter[]{new EditInputFilter(100, 0, 0)});
        binding.etWarrantyTime.setFilters(new EditInputFilter[]{new EditInputFilter(99999999, 1, 0)});
        binding.marginMoney.setFilters(new EditInputFilter[]{new EditInputFilter(99999999, 1, 0)});
    }

    public boolean submit() {
        PublishLeaseDataEntity.AttachDTO attachDTO = viewModel.bean.getAttach();
        String invoiceType = binding.itvInvoiceType.getContent();
        if (invoiceType.equals("普通发票") || invoiceType.equals("专用发票")) {
            String shuilv = binding.itvShuiLv.getContent();
            if (TextUtils.isEmpty(shuilv)) {
                MToast.showToast(getActivity(), "请选择税率!");
                return false;
            }
        }


        if (type != 2) {
            String warranty = binding.etWarrantyMoney.getText().toString().trim();//保证金
            if (!TextUtils.isEmpty(warranty)) {
                attachDTO.setWarranty(warranty);
            }
            String warranty_time = binding.etWarrantyTime.getText().toString().trim();//保质期
            if (!TextUtils.isEmpty(warranty_time)) {

                attachDTO.setWarrantyPeriod(warranty_time);
            }
        }
        String margin_money = binding.marginMoney.getText().toString().trim();//履约保证金
        attachDTO.setPerformanceBond(margin_money);
        String driverSalaryBonus = binding.driverSalaryBonus.getEditContent();//驾驶员薪酬奖励
        attachDTO.setDriverSalaryBonus(driverSalaryBonus);
        String driverStaying = binding.driverStaying.getEditContent();//驾驶员食宿
        attachDTO.setDriverStaying(driverStaying);
        String fuelCosts = binding.fuelCosts.getEditContent();//燃油费用
        attachDTO.setFuelCosts(fuelCosts);
        String repairCosts = binding.repairCosts.getEditContent();//维修费用
        attachDTO.setRepairCosts(repairCosts);
        String entryExitFees = binding.entryExitFees.getEditContent();//进退场费用
        attachDTO.setEntryExitFees(entryExitFees);
        String sparePartsCost = binding.sparePartsCost.getEditContent();//零配件费用
        attachDTO.setSparePartsCost(sparePartsCost);
        String maintenanceCost = binding.maintenanceCost.getEditContent();//保养费用
        attachDTO.setMaintenanceCost(maintenanceCost);
        String insuranceFee = binding.insuranceFee.getEditContent();//保险费用
        attachDTO.setInsuranceFee(insuranceFee);
        String accident = binding.accident.getEditContent();//意外事故
        attachDTO.setAccident(accident);
        if (getViewList2()) {
            attachDTO.setExtra(viewList);
        }else {
            return false;
        }
        viewModel.bean.setAttach(attachDTO);
        return true;
    }


    @Override
    public void OnWholeItemClick(View view) {
        switch (view.getId()) {
            case R.id.itv_invoice_type:
                pickerView1.show();
                break;
            case R.id.itv_shui_lv:
                pickerView2.show();
                break;
        }
    }

    /**
     * 发票类型
     */
    private void showPop1() {
        pickerView1 = new OptionsPickerBuilder(getActivity(), (options1, options2, options3, v) -> {
            String content = invoiceGGDatas.get(options1).getProjectscale();
            binding.itvInvoiceType.setContent(content);
            viewModel.bean.getAttach().setInvoiceType(invoiceGGDatas.get(options1).getNo());
            if ("不需要发票".equals(content)) {
                binding.itvShuiLv.setVisibility(View.GONE);
                viewModel.bean.getAttach().setTariff("");
            } else {
                binding.itvShuiLv.setVisibility(View.VISIBLE);
            }
        }).build();
        pickerView1.setPicker(invoiceGGDatas);
    }

    /**
     * 利率
     */
    private void showPop2() {
        pickerView2 = new OptionsPickerBuilder(getActivity(), (options1, options2, options3, v) -> {
            String content = shuilvDatas.get(options1).getProjectscale();
            binding.itvShuiLv.setContent(content);
            viewModel.bean.getAttach().setTariff(content);
        }).build();
        pickerView2.setPicker(shuilvDatas);
    }

    private void showPop3() {
        pickerView3 = new OptionsPickerBuilder(getActivity(), (options1, options2, options3, v) -> {
            String content = timeTypeData.get(options1).getProjectscale();
            binding.tvDay.setText(content);
            viewModel.bean.getAttach().setWarrantyPeriodUnit(content);
        }).build();
        pickerView3.setPicker(timeTypeData);
        if(TextUtils.isEmpty(id)){
            viewModel.bean.getAttach().setWarrantyPeriodUnit("日");
        }
    }

    private void addView() {
        if (binding.llDescGroup.getChildCount() >= 5) {
            MToast.showToast(getActivity(), "最多只能新增5条");
            return;
        }
        if (!getViewList()) {
            return;
        }
        View view = View.inflate(getActivity(), R.layout.layout_lease_ask_item, null);
        binding.llDescGroup.addView(view, binding.llDescGroup.getChildCount());
        TextView tvDel = view.findViewById(R.id.tv_del);
        tvDel.setOnClickListener(view1 -> binding.llDescGroup.removeView(view));
        if (binding.llDescGroup.getChildCount() > 1) {
            View itemView = binding.llDescGroup.getChildAt(binding.llDescGroup.getChildCount() - 2);
            itemView.findViewById(R.id.tv_del).setVisibility(View.VISIBLE);
        }
        binding.tvDelView.setVisibility(View.VISIBLE);
    }

    private void delView() {
        if (binding.llDescGroup.getChildCount() > 0) {
            binding.llDescGroup.removeViewAt(binding.llDescGroup.getChildCount() - 1);
            if (binding.llDescGroup.getChildCount() == 0) {
                binding.tvDelView.setVisibility(View.GONE);
            } else {
                View itemView = binding.llDescGroup.getChildAt(binding.llDescGroup.getChildCount() - 1);
                itemView.findViewById(R.id.tv_del).setVisibility(View.GONE);
            }
        }

    }

    public boolean getViewList() {
        viewList.clear();
        for (int i = 0; i < binding.llDescGroup.getChildCount(); i++) {
            View view = binding.llDescGroup.getChildAt(i);
            String title = ((EditText) view.findViewById(R.id.tv_desc_title)).getText().toString().trim();
            String content = ((CfkEditView) view.findViewById(R.id.tv_desc_content)).getEditContent().trim();
            if (TextUtils.isEmpty(title) || TextUtils.isEmpty(content)) {
                MToast.showToast(getActivity(), "请完善新增说明");
                return false;
            }
            PublishLeaseDataEntity.ParamBean bean = new PublishLeaseDataEntity.ParamBean();
            bean.setTitle(title);
            bean.setContent(content);
            viewList.add(bean);
        }
        return true;
    }

    public boolean getViewList2() {
        viewList.clear();
        for (int i = 0; i < binding.llDescGroup.getChildCount(); i++) {
            View view = binding.llDescGroup.getChildAt(i);
            String title = ((EditText) view.findViewById(R.id.tv_desc_title)).getText().toString().trim();
            String content = ((CfkEditView) view.findViewById(R.id.tv_desc_content)).getEditContent().trim();
            if (TextUtils.isEmpty(title) && !TextUtils.isEmpty(content)) {
                MToast.showToast(getActivity(), "请完善新增说明");
                return false;
            }
            if (!TextUtils.isEmpty(title) && TextUtils.isEmpty(content)) {
                MToast.showToast(getActivity(), "请完善新增说明");
                return false;
            }
            if (!TextUtils.isEmpty(title) && !TextUtils.isEmpty(content)) {
                PublishLeaseDataEntity.ParamBean bean = new PublishLeaseDataEntity.ParamBean();
                //bean.setNo(i);
                bean.setTitle(title);
                bean.setContent(content);
                viewList.add(bean);
            }
        }
        return true;
    }

}
